/*
 * Serum
 *
 * @license      GNU Lesser General Public Licence see LICENCE-LGPL file or http://www.gnu.org/licenses/lgpl.html
 */

Serum.Form.Module.Abstract = Ext.extend(Ext.FormPanel, {

    /**
     * Constructor
     *
     */
    constructor: function(config, selector, onSuccess) {
        Serum.Form.Module.Abstract.superclass.constructor.call(this, Ext.apply({}, config));
    },

    /**
     * Returns form fields list
     *
     * If null, all fields will be displayed.
     * Expected format :
     * {'fieldset': [{'fieldname': {'option1': 'value', 'option2': 'value'}, {'fieldname', {}}],
     *  'otherfieldset': [ ... ]}
     *
     * @param   {Object}    results     Results with values
     * @return  {Object}    Fields list
     */
    fieldsList: function(results) {
        return null;
    },

    /**
     * Returns form title
     *
     * @return  {String}
     */
    getTitle: function() {
        return __('base~form_search_title');
    },

    /**
     * Returns the top toolbar
     *
     * @return  {Array}
     */
    getTopToolbar: function() {
        return null;
    },

    isFormAction:           function() {},
    load:                   function() {},
    preload:                function(elementId) {},
    build:                  function(fieldsList) {},
    defaultLabelWidth:             140,

    /**
     * Private build
     *
     * @param   {Object}    response    Fields list
     * @param   {Object}    fieldsList
     */
    _build: function(response, fieldsList) {
        var elementId       = this.getElementId();
        var fieldsets       = response['fields'];
        var generatedList   = {};
        var newField        = {};
        var fieldset        = null;
        var fieldsetObj     = null;
        var field           = null;
        var i               = 0;
        var currentLanguage = Serum.Selector.get().language

        // Parse generated fields
        for (var _fieldset in fieldsets) {
            // Foreach fieldset
            fieldset = fieldsets[_fieldset];

            for (var _field in fieldset) {
                field = fieldset[_field];
                if (!['status', 'creation_date', 'last_modification_date', 'root_id', 'lft', 'rgt', 'level'].contains(field['fieldname'])) {
                    // Some fields won't be displayed
                    newField                = {};
                    newField['name']        = field['fieldname'];
                    newField['labelWidth']  = this.defaultLabelWidth;
                    newField['fieldLabel']  = field['fieldLabel'] || __(this.module.toLowerCase() + '~form_label_' + field['fieldname']);
                    newField['maxLength']   = field['length'];

                    // I18n
                    if (field['i18n'] === true) {
                        field['value']      = field['value'][currentLanguage];
                        newField['name']    = 'i18n-' + currentLanguage + '-' + newField['name'];
                    }

                    // Validators
                    if (typeof field['validators'] !== 'undefined') {
                        var validators = field['validators'];

                        if (typeof validators['notblank'] !== 'undefined' || typeof validators['notnull'] !== 'undefined') {
                            newField['allowBlank'] = false;
                        }

                        if (typeof validators['email'] !== 'undefined') {
                            newField['vtype'] = 'email';
                        }
                    }

                    // Readonly
                    if (typeof field['readonly'] !== 'undefined' && field['readonly'] === true) {
                        newField['readOnly'] = true;
                    }

                    // Type
                    switch(field['type']) {
                        case 'boolean':
                            newField['checked']   = (field['value'] == 1);
                            newField['xtype']     = 'xcheckbox';
                            break;

                        case 'date':
                            newField['format']    = "d/m/Y";
                            newField['value']     = field['value']['date'];
                            newField['xtype']     = 'datefield';
                            newField['name']      = 'date-' + field['fieldname'];
                            break;

                        case 'i18n':
                            if (field['length'] <= 255) {
                                newField['xtype']     = 'textfield';
                            } else {
                                newField['xtype']     = 'textarea';
                            }
                            break;

                        case 'time':
                            newField['format']    = "H:i";
                            newField['value']     = field['value']['time'];
                            newField['xtype']     = 'timefield';
                            newField['name']      = 'time-' + field['fieldname'];
                            break;

                        case 'timestamp':
                            newField['dateFormat']= 'd/m/Y';
                            newField['value']     = field['value']['date'] + ' ' + field['value']['time'];
                            newField['timeFormat']= 'H:i';
                            newField['xtype']     = 'datetimefield';
                            newField['name']      = 'timestamp-' + field['fieldname'];
                            break;

                        case 'relation1to1':
                            newField['forceSelection']    = true;
                            newField['mode']              = 'local';
                            newField['displayField']      = '__toString';
                            newField['valueField']        = 'id';

                            var store                   = new Ext.data.SimpleStore({
                                fields: ['id', '__toString'],
                                data:   field['values']
                            });
                            newField['store']             = store;
                            newField['xtype']             = 'combo';
                            newField['triggerAction']     = 'all';
                            newField['value']             = field['value'];
                            newField['hiddenName']        = 'rel-' + field['fieldname'];
                            break;

                        case 'enum':
                            newField['items'] = [];
                            for(i = 0; i < field['values'].length; i++) {
                                newField['items'].push({
                                    boxLabel:   field['values'][i],
                                    inputValue: field['values'][i],
                                    name:       field['fieldname'],
                                    checked:    (field['value'] == field['values'][i])
                                });
                            }
                            newField['columns']   = 2;
                            newField['vertical']  = true;
                            newField['xtype']     = 'radiogroup';
                            break;

                        case 'relation1toN':
                            newField['items'] = [];

                            if (field['value'] === null) {
                                field['value'] = [];
                            } else if (!(field['value'] instanceof Array)) {
                                field['value'] = [field['value']];
                            }

                            for(var onetonItem in field['values']) {
                                if (typeof field['values'][onetonItem] !== 'function') {
                                    newField['items'].push({
                                        name:       'rel-' + field['fieldname'] + '-' + field['values'][onetonItem][0],
                                        boxLabel:   field['values'][onetonItem][1],
                                        checked:    (field['value'].contains(field['values'][onetonItem][0])),
                                        xtype:      'checkbox'
                                    });
                                }
                            }

                            if (newField['items'].length == 0) {
                                continue;
                            }

                            newField['columns']   = 2;
                            newField['vertical']  = true;
                            newField['xtype']     = 'checkboxgroup';
                            break;

                        case 'nested':
                            newField['xtype']       = 'hidden';
                            newField['name']        = 'rel-' + field['fieldname'];
                            newField['value']       = field['value'];
                            break;

                        case 'integer':
                            newField['decimalPrecision']    = 0;
                        case 'float':
                        case 'decimal':
                        case 'double':
                            newField['xtype']                   = 'numberfield';
                            newField['value']                   = field['value'];
                            if (field['decimalPrecision'] !== undefined) {
                                newField['decimalPrecision']    = field['decimalPrecision'];
                            }
                            break;

                        case 'label':
                            newField['xtype']                   = 'label';
                            newField['text']                    = field['fieldLabel'];
                            break;

                        case 'string':
                        default:
                            if (field['fieldname'].substr(0, 4) === 'file') {
                                newField['value']       = field['value'];
                                newField['preview']     = field['preview'];
                                newField['xtype']       = 'uploadpreviewfield';

                            } else if (field['fieldname'].substr(0, 8) === 'password') {
                                newField['xtype']       = (this.isEditForm()) ? 'editpasswordfield' : 'newpasswordfield';

                            } else {
                                newField['value'] = field['value'];

                                if (field['length'] <= 255) {
                                    newField['xtype']           = 'textfield';

                                } else {
                                    newField['xtype']           = 'tinymce';
                                    newField['width']           = '100%';
                                    newField['height']          = 300;
                                    newField['tinymceSettings'] = { theme: "advanced",
                                                                    entity_encoding: "named",
                                                                    plugins: "safari,advlink,iespell,contextmenu,paste,noneditable,visualchars,nonbreaking,fullscreen,advimage,style",
                                                                    theme_advanced_buttons1 : "image,|,bold,italic,underline,formatselect,|,justifyleft,justifycenter,justifyright,justifyfull",
                                                                    theme_advanced_buttons2 : "bullist,numlist,|,cut,copy,pastetext,pasteword,|,link,unlink,|,code,|,fullscreen,blockquote",
                                                                    theme_advanced_buttons3 : "",
                                                                    theme_advanced_toolbar_location : "top",
                                                                    theme_advanced_toolbar_align : "left",
                                                                    theme_advanced_statusbar_location : "bottom",
                                                                    theme_advanced_resizing : false,
                                                                    file_browser_callback : "fileBrowserCallBack"
                                                                };
                                    
                                }
                            }
                            break;
                    }

                    generatedList[field['fieldname']] = newField;
                }
            }

            this.add(fieldsetObj);
        }

        if (typeof fieldsList === 'undefined') {
            fieldsList = this.fieldsList(fieldsets);
        }

        if (typeof fieldsList === 'undefined' || fieldsList === null) {
            // We put all generated fields
            fieldsetObj = new Ext.form.FieldSet({
                title:          __('base~form_fieldset_default'),
                collapsible:    true,
                autoHeight:     true,
                labelWidth:     this.defaultLabelWidth
            });

            for(_field in generatedList) {
                // Foreach field
                if (!['id'].contains(_field)) {
                    field = generatedList[_field];
                    fieldsetObj.add(field);
                }
            }

            this.add(fieldsetObj);

        } else {
            // List of fields is specified
            for(_fieldset in fieldsList) {
                // Foreach fieldset
                fieldset = fieldsList[_fieldset];

                var fieldsetConfig = fieldset[1] || {};

                fieldsetObj = new Ext.form.FieldSet(Ext.apply({
                    title:          __(this.module.toLowerCase() + '~form_fieldset_' + _fieldset, 'base~form_fieldset_' + _fieldset),
                    collapsible:    true,
                    autoHeight:     true,
                    labelWidth:     this.defaultLabelWidth

                }, fieldsetConfig));

                for(var _fieldname in fieldset[0]) {
                    var options = fieldset[0][_fieldname];

                    if (typeof generatedList[_fieldname] !== 'undefined') {
                        var defaultField = generatedList[_fieldname];

                        for(var optionName in options) {
                            // Overrides options
                            defaultField[optionName] = options[optionName];
                        }

                        fieldsetObj.add(defaultField);

                    } else if (typeof options['xtype'] !== 'undefined') {
                        fieldsetObj.add(options);
                    }
                }

                if (typeof fieldsetObj.items !== 'undefined' && fieldsetObj.items.getCount() > 0) {
                    this.add(fieldsetObj);
                }
            }
        }

        // Hidden fields
        this.add(new Ext.form.Hidden({
            name:   '_model',
            value:  response['model'],
            id:     '_model'
        }));

        this.add(new Ext.form.Hidden({
            name:   '_prevAction',
            value:  response['action']
        }));

        if (elementId !== null) {
            if (elementId instanceof Array) {
                this.add(new Ext.form.Hidden({
                    name:   'idList',
                    value:  elementId.implode('-')
                }));
            } else {
                this.add(new Ext.form.Hidden({
                    name:   'id',
                    value:  elementId
                }));
            }
        }

        this.add(new Ext.form.Hidden({
            name:   'todoaction',
            value:  (elementId !== null) ? 'edit' : 'add'
        }));

        this.fireEvent('formbuilded');

        // Refreshes form
        this.doLayout();
        this.cleanErrors();
    },

    /**
     * Returns currently edited element id
     *
     * @return  {Integer}   Currently edited element id
     */
    getElementId: function() {
        return this.elementId;
    }
});

/**
 * TinyFCK browser callback
 */
function fileBrowserCallBack(field_name, url, type, win) {
	var connector = Serum.Selector.get().rootUrl + 'filemanager/browser.html?Connector=connectors/php/connector.php';
	var enableAutoTypeSelection = true;

	var cType;
	tinyfck_field = field_name;
	tinyfck = win;

	switch (type) {
		case "image":
			cType = "Image";
			break;
		case "flash":
			cType = "Flash";
			break;
		case "file":
			cType = "File";
			break;
	}

	if (enableAutoTypeSelection && cType) {
		connector += "&Type=" + cType;
	}

    window.open(connector, 'tinyfck' + Serum.Helper.Request.id(), 'modal,width=600,height=400');
}
